import json
import re
import logging
from django.contrib.auth import login, authenticate, logout
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse, HttpResponse
from apps.user.models import User
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection

# Create your views here.
from libs.yuntongxun.sms import CCP


class RegisterView(View):
    """注册"""

    def post(self, request):
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        phonecode = data.get('phonecode')
        password = data.get('password')

        # 验证参数
        if not all([mobile, phonecode, password]):
            return JsonResponse({"errno": 4001, "errmsg": "参数不全"})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 4001, 'errmsg': '手机号格式有误'})

        count = User.objects.filter(username=mobile).count()
        if count != 0:
            return JsonResponse({'errno': 4001, 'errmsg': '该手机号已注册'})

        redis_cli = get_redis_connection('code')
        sms_code = redis_cli.get('sms_%s' % mobile)
        if sms_code is None:
            return JsonResponse({'errno': 4001, 'errmsg': '短信验证码已失效'})
        if int(phonecode) != int(sms_code):
            return JsonResponse({'errno': 4001, 'errmsg': '短信验证码不正确'})

        try:
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        except:

            return JsonResponse({'errno': 4103, 'errmsg': '注册失败'})

        login(request, user)

        return JsonResponse({'errno': 0, 'errmsg': '注册成功'})


class ImageView(View):
    """图片验证码"""

    def get(self, request):
        # 获取验证码编号
        cur = request.GET.get('cur')

        # 生成图片验证码
        # text 验证码内容
        # image 验证码图片
        text, image = captcha.generate_captcha()
        redis_cli = get_redis_connection('code')
        redis_cli.setex('image_%s' % cur, 300, text)

        return HttpResponse(image)


class SmscodeView(View):
    """短信验证码"""

    def post(self, request):
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        # 图片验证码编号
        id = data.get('id')
        # 图片验证码内容
        text = data.get('text')
        if not all([mobile, id, text]):
            return JsonResponse({'errno': 4001, 'errmsg': '数据错误'})
        redis_cli = get_redis_connection('code')

        b_image_code = redis_cli.get('image_%s' % id)
        if b_image_code is None:
            return JsonResponse({'errno': 4001, 'errmsg': '图片验证码已过期'})
        # 转换类型
        image_code = b_image_code.decode()
        if image_code.lower() != text.lower():
            return JsonResponse({'errno': 4001, 'errmsg': '验证码输入有误'})
        import random
        sms_code = "%06d" % random.randint(0, 999999)

        redis_cli.setex('sms_%s' % mobile,300,sms_code)
        # 发送验证码
        from celery_tasks.sms.tasks import celery_send_sms_code
        celery_send_sms_code.delay(mobile=mobile, code=sms_code)

        return JsonResponse({'errno': 0, 'errmsg': '发送成功'})


# *****************登录************************

class LoginView(View):
    # 登录
    def post(self, request):

        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        password = data.get('password')
        if not all([mobile, password]):
            return JsonResponse({'errno': 4001, 'errmsg': '参数不全'})
        user = authenticate(username=mobile, password=password)
        if user is None:
            return JsonResponse({'errno': 4001, 'errmsg': '账号或密码错误'})
        login(request, user)

        response = JsonResponse({'errno': 0, 'errmsg': '登录成功'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        return response

    def get(self, request):
        """判断是否登录"""
        user = request.user
        user_id = user.id
        if user is None:
            return JsonResponse({'errno': 4101, 'errmsg': '用户未登录'})
        response = JsonResponse({'errno': 0, 'errmsg': '登录成功', 'data': {'user_id': user_id, 'name': user.username}})
        return response

    def delete(self, request):
        """退出"""
        logout(request)
        response = JsonResponse({'errno': 0, 'errmsg': '退出成功'})
        response.delete_cookie('username')
        # 删除cookie
        return response
